package club.cearnach.api.security.service;

import club.cearnach.api.exception.AdminException;
import club.cearnach.api.service.IAdminService;
import club.cearnach.core.property.MovieSecurityProperties;
import club.cearnach.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 阮胜
 * @date 2018/5/23 15:09
 */
@Component
@Qualifier("adminDetailService")
public class AdminUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private MovieSecurityProperties movieSecurityProperties;

    public AdminUserDetailServiceImpl(IAdminService adminService) {
        this.adminService = adminService;
    }

    private final IAdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.findByAccount(username)
                .orElseThrow(() -> new UsernameNotFoundException(AdminException.ADMIN_CAN_NOT_FOUNT));
        String role = movieSecurityProperties.getRolePrefix().concat(admin.getRole().getName());
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(role);
        return new User(admin.getAccount(), admin.getPassword(), authorities);
    }
}
